using System;
using System.Collections.Generic;
using System.Linq;
using axCommerce.Data.Interface;

namespace axCommerce.Data
{
	public partial class Account : ISimpleData
	{
		public List<Permission> Permissions { get; set; }

		private void FillPermissions()
		{
			if (AccountId.HasValue)
				Permissions = Permission.Search(null, AccountId);
		}

		public static List<Account> GetAllAccounts()
		{
			return (from customer in Customer.GetAllCustomers()
					where customer.CustomerInfo != null && customer.CustomerInfo.AccountInfo != null
					select customer.CustomerInfo.AccountInfo).ToList();
		}

		public Account SearchById(int iAccountId)
		{
			return Get(iAccountId);
		}

		public static Account SearchByEmail(string sEmail)
		{
			return Search(new Account
							{
								Email = sEmail
							}).FirstOrDefault();
		}

		public static Account SearchByPasswordKey(string sNewPasswordKey)
		{
			return Search(new Account
							{
								NewPasswordKey = sNewPasswordKey
							}).FirstOrDefault();
		}

		public void UpdateInstance()
		{
			LastModifiedDate = DateTime.Now;

			Update();
		}

		public void MarkAsDeleted()
		{
			foreach (Customer customer in
						Customer.GetAllCustomers().Where(
							customer => customer.CustomerInfo != null && customer.CustomerInfo.AccountInfo != null).Where(
								customer => customer.CustomerInfo.AccountInfo.AccountId == AccountId))
			{
				customer.MarkAsDeleted();
			}
		}

		public void Save()
		{
			CreatedDate = DateTime.Now;
			IsLockedOut = false;
			LastLockedOutDate = DateTime.Now;
			LastLoginDate = DateTime.Now;
			NewEmailKey = Guid.NewGuid().ToString();
			NewPasswordKey = Guid.NewGuid().ToString();

			Insert();
		}
	}
}

